package com.zll.shirotest.shiro;

import com.zll.shirotest.constants.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * 重写sessionmanager
 * @author zll
 */
public class ShiroSessionManager extends DefaultWebSessionManager {

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpRequest = WebUtils.getHttpRequest(request);
        String sessionId = httpRequest.getHeader(Constants.HEADER_AUTHRIZATION);
        if (StringUtils.isEmpty(sessionId)) {
            return super.getSessionId(request, response);
        }
        //设置sessionid来源
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, Constants.REFERENCED_SESSION_ID_SOURCE);
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
        //设置sessionid经过校验
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
        return sessionId;
    }
}
